<template>
  <view class="bg" :style="{ height: bgHeight + 'px' }">
    <view class="main-box" :style="{ height: bgHeight * 0.84 * 2 + 'rpx' }">
      <view class="weather-box">
        <view class="weather-box-item-value">{{ weatherDay.weather }}
          <img src="@/static/icon/weather_logo.png" alt="" class="weather-logo" />
        </view>
        <view class="weather-box-item-city">{{ weatherDay.city }}</view>
        <view class="weather-box-item-weather"> </view>
        <p class="weather-box-item-weather-text">
          {{ weatherDay.winder }} {{ weatherDay.minweather }}℃~{{
            weatherDay.maxweather
          }}℃
        </p>
      </view>
      <view class="ana-title">{{ Textana }}</view>
    </view>
    <view class="camera-box" @click="takePhoto">
      <img class="camera-box-item-img" src="@/static/icon/camera.png" alt="" />
      <view class="camera-box-item-title">拍照上传</view>
    </view>
    <up-toast ref="uToastRef" />
  </view>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from "vue";
import { useMemberStore } from "@/stroes/modules/member";
const { safeArea } = uni.getSystemInfoSync();
const bgHeight = ref(safeArea!.height - safeArea!.top);
import { getCaregoryAPI } from "@/api/caregory";
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import { getAnaAPI } from "@/api/ana";
import { postAPI, postDailyAPI } from "@/api/user";
import { requests } from "@/utlis/request";
import { useWeatherStore } from "@/stroes/modules/weather";
const memberStore = useMemberStore();
const weatherStore = useWeatherStore();
const Textana = ref();

// 点击拍照按钮
const takePhoto = () => {
  // 这里模拟拍照完成后提示
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"], // 推荐压缩图
    sourceType: ["album", "camera"],
    quality: 70, // 压缩质量 0-100
    success: (res) => {
      const tempFilePath: any = res.tempFilePaths[0];
      if (tempFilePath.size > 10 * 1024 * 1024) {
        uni.showToast({ title: "请选择小于10MB的图片", icon: "none" });
        return;
      }
      // 跳转到更新衣物页面，并传递图片路径
      uni.navigateTo({
        url: `/pages/update_clothes/update_clothes?imageUrl=${tempFilePath}`,
      });
    },
    fail: (err) => {
      console.error("选择图片失败", err);
      uni.showToast({
        title: "选择图片失败",
        icon: "none",
      });
    },
  });
};
const weatherDay = reactive({
  weather: 0,
  minweather: 0,
  maxweather: 0,
  winder: "",
  city: "",
});
// 判断是否已经登录
const isLogin = async () => {
  if (!memberStore.userinfo.token) {
    return doLogin();
  }
  try {
    await getAnaAPI();
    request();
    DailyCount();
    AnaData();
  } catch (err) {
    // token 失效 → 重新登录
    doLogin();
  }
};
const doLogin = () => {
  uni.login({
    provider: "weixin",
    success: (res) => {
      const code = res.code;
      // 调用后端接口
      uni.request({
        url: "/user/login",
        method: "POST",
        data: {
          code: code,
          username: " ",
          avatar: " ",
          phone: " ",
        },
        success: (res: any) => {
          const { data } = res.data;
          if (res.data) {
            // console.log("登录成功", data);
            memberStore.setuserinfo(data);
            // console.log(
            //   "memberStore.userinfo解包",
            //   JSON.parse(JSON.stringify(memberStore.userinfo))
            // );
            request();
            DailyCount();
            AnaData();
          } else {
            uni.showToast({ icon: "none", title: res.data.message });
          }
        },
        fail: () => {
          uni.showToast({ icon: "none", title: "请求失败" });
        },
      });
    },
  });
};
const request = async () => {
  try {
    await postAPI({ uri: "miniapp" });
  } catch (error) { }
};

const DailyCount = async () => {
  await postDailyAPI({ uri: "daily" });
};

// 2. 获取天气信息（使用经纬度）
const getWeather = async (latitude: number, longitude: number) => {
  try {
    const res: any = await requests({
      url: `https://apis.map.qq.com/ws/weather/v1/`,
      method: "GET",
      data: {
        location: `${latitude},${longitude}`, // 直接使用经纬度
        key: "FL4BZ-7B23T-JMNX5-LP22A-IUAVK-TDFR4",
      },
    });
    const kont = res.result.realtime[0];
    const core = kont;
    weatherDay.city = `${kont.city} ${kont.district}`;
    weatherDay.maxweather = core.infos.temperature + 2;
    weatherDay.minweather = core.infos.temperature - 2;
    weatherDay.weather = core.infos.temperature;
    weatherDay.winder = core.infos.weather;
  } catch (err) {
    return null;
  }
};
// Toast 引用
const uToastRef = ref<any>(null);

// 显示默认 Toast
const showToast = () => {
  uToastRef.value?.show({
    message: "刷新成功",
    duration: 1500, // 显示时间
    position: "top", // top, center, bottom
  });
};
// 统一封装：获取定位并刷新天气
const refreshWeather = async () => {
  return new Promise<void>((resolve, reject) => {
    uni.getLocation({
      type: "wgs84",
      success: async (res) => {
        const { latitude, longitude } = res;
        console.log("经纬度", latitude, longitude);
        await getWeather(latitude, longitude);
        resolve();
      },
      fail(err) {
        console.error("获取位置失败", err);
        reject(err);
      },
    });
  });
};
const AnaData = async () => {
  const res: any = await getAnaAPI();
  Textana.value = res.text;
};

// 下拉刷新
onPullDownRefresh(async () => {
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 1000);
  await refreshWeather();
  showToast();
});

// 页面加载
onLoad(() => {
  isLogin();
  refreshWeather();
});
</script>

<style lang="scss" scoped>
page {
  background-color: #f5f5f5;
}

// 为了确保样式生效，添加一个全局样式
:deep(uni-page-body) {
  background-color: #f5f5f5;
}

// 为了保证页面高度100%，给page下的第一个元素设置高度
.bg {
  min-height: 100vh;
  overflow: hidden;

  .main-box {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border-radius: 0 0 20% 20%;
    overflow: hidden;
    background-image: url("http://132.232.132.248:8880/group1/M00/00/00/CgYABGgzRxyAdqSmABJXIT1hHfg54..png");
    background-size: cover;
    background-position: 40% 50%;
    background-repeat: no-repeat;

    .weather-box {
      width: 440rpx;
      height: 440rpx;
      display: flex;
      border-radius: 10%;
      flex-direction: column;
      align-items: center;
      background-color: rgba(255, 255, 255, 0.4);

      .weather-box-item-value {
        position: relative;
        height: 180rpx;
        line-height: 180rpx;
        margin-top: 50rpx;
        font-size: 140rpx;
        // color: #000000;
        color: #fff;

        .weather-logo {
          position: absolute;
          top: 5rpx;
          right: -20rpx;
          width: 32rpx;
          height: 32rpx;
        }
      }

      .weather-box-item-city {
        font-size: 36rpx;
        margin: 30rpx 0;
        // color: #000000;
        color: #fff;
      }

      .weather-box-item-weather-text {
        font-size: 36rpx;
        // color: #000000;
        color: #fff;
        font-weight: 500;
      }
    }
  }

  .camera-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 340rpx;
    height: 340rpx;
    border-radius: 50%;
    margin: 0 auto;
    overflow: hidden;
    transform: translateY(-50%);
    background-color: #fff;

    .camera-box-item-img {
      margin: 12rpx 0;
      width: 126rpx;
      height: 90rpx;
    }

    .camera-box-item-title {
      font-size: 46rpx;
      color: #000000;
    }
  }

  .camera-box-item-img {
    width: 100%;
    height: 100%;
  }

  .camera-box-item-title {
    font-size: 28rpx;
    color: #333;
  }
}

.ana-title {
  margin-top: 30rpx;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: bold;
}
</style>
